package com.cs307.redcross.client;

import java.io.Serializable;
import java.security.MessageDigest;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;

public class ValidateIdentityDialogBox extends DialogBox implements Serializable {

	private static final long serialVersionUID = 4468006641815672683L;
	private DatabaseHandlerServiceAsync databaseHandlerService = (DatabaseHandlerServiceAsync) GWT.create(DatabaseHandlerService.class);
	Boolean isLogin = false;
	int sessionID = 0;

	AbsolutePanel absolutePanel;
	TextBox userID;
	Button confirmButton, cancelButton;
	Label lblPassword;
	PasswordTextBox passwordTextBox;
	boolean isValid = false;
	
	Vector<Volunteer> volunteerVector;
	
	public ValidateIdentityDialogBox() {
		this.setText("Validate Identity");
		
		absolutePanel = new AbsolutePanel();
		setWidget(absolutePanel);
		absolutePanel.setSize("211px", "165px");
		
		userID = new TextBox();
		confirmButton = new Button("Change");
		confirmButton.setText("Confirm");
		cancelButton = new Button("Cancel");
		
		Label label_1 = new Label("Admin Email:");
		absolutePanel.add(label_1, 10, 10);
		label_1.setSize("91px", "18px");
		absolutePanel.add(userID, 10, 28);
		userID.setSize("180px", "13px");
		
		absolutePanel.add(confirmButton, 10, 127);
		confirmButton.setSize("85px", "24px");
		absolutePanel.add(cancelButton, 131, 127);
		cancelButton.setSize("67px", "24px");
		
		confirmButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				
				if (userID.getText().replaceAll(" ","").equals("")) {
					Window.alert("Email address required.");
					return;
				}
				if (passwordTextBox.getText().replaceAll(" ","").equals("")) {
					Window.alert("Password required.");
					return;
				}
				if (Server.currentUser != null && !userID.getText().equals(Server.currentUser.getEmail())) {
					Window.alert("The email address entered does not match the email address of the currently logged in user.");
					return;
				}
				
				// gets the usernames and passwords from the login screen  
				String enteredUsername = userID.getText();
				String enteredPassword = Person.encrypt(passwordTextBox.getText());
												
				// calls the server to check for valid username password
				databaseHandlerService.validPassword(enteredUsername, enteredPassword, new AsyncCallback<Integer>() {
					public void onFailure(Throwable caught) {
						Window.alert("Cannot connect the server to verify identity. Please exit and then log back into the system.");
					}
					
					public void onSuccess(Integer result) {
						if(result > -1) {
							isValid = true;
							hide();
						}
						else 
						{
							Window.alert("You have entered an incorrect password");
							isValid = false;
						}
					}
				});
			}
		  });
		
		cancelButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				hide();
			}
		  });
		
		userID.setFocus(true);
		
		lblPassword = new Label("Password:");
		absolutePanel.add(lblPassword, 10, 66);
		lblPassword.setSize("91px", "18px");
		
		passwordTextBox = new PasswordTextBox();
		absolutePanel.add(passwordTextBox, 10, 90);
		passwordTextBox.setSize("180px", "13px");
	}
	//based on code from http://www.java2s.com/Tutorial/Java/0490__Security/Createanencryptedstringforpassword.htm
	private String encrypt(String password )
	{
		 String algorithm = "SHA";

	        byte[] plainText = password.getBytes();

	        MessageDigest md = null;

	        try {		
	            md = MessageDigest.getInstance(algorithm);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
			
	        md.reset();		
	        md.update(plainText);
	        byte[] encodedPassword = md.digest();

	        StringBuilder sb = new StringBuilder();
	        for (int i = 0; i < encodedPassword.length; i++) {
	            if ((encodedPassword[i] & 0xff) < 0x10) {
	                sb.append("0");
	            }

	            sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
	        }
		return sb.toString();
	}

}
